package org.spring.data.jpa.demo.controller;

import org.spring.data.jpa.demo.dao.UserDao;
import org.spring.data.jpa.demo.dto.UserDTO;
import org.spring.data.jpa.demo.entity.User;
import org.spring.data.jpa.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @date 2021/9/6
 * @auther uranus
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    UserDao userDao;
    @Autowired
    UserService userService;

    /**
     * 访问：http://localhost:9020/user/get?name=张三
     * SQL注入： http://localhost:9020/user/get?name=' or 1=1 or name= '
     * @param name
     * @return
     */
    @GetMapping("/get")
    public List getUsers(@RequestParam("name")String name){
        String sql="select id,name from user where name='"+name+"'";
        List<Map<String,Object>> maps=jdbcTemplate.queryForList(sql);
        return maps;
    }

    /**
     * 修改jpa访问
     * @param name
     * @return
     */
    @GetMapping("get1")
    public List<User> getUsersDao(@RequestParam("name")String name){
        return userDao.findByName(name);
    }
    /**
     * #####################################################################
     */
    @PostMapping
    public UserDTO create(@RequestBody UserDTO dto){
        return userService.create(dto);
    }
    @PutMapping("/{id}")
    public UserDTO update(@RequestBody UserDTO dto){
        return userService.update(dto);
    }
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id")String id){
        userService.delete(id);
    }
    @GetMapping("/{id}")
    public UserDTO getUserById(@PathVariable("id")String id,
                               HttpServletRequest request){
        User user=(User)request.getAttribute("user");
        System.out.println(user);
        if(user!=null && user.getId().equals(id)){
            return userService.getById(id);
        }else{
            throw new RuntimeException("身份认证信息异常，获取用户信息失败");
        }
    }
}
